//
//  Monkey_DefenseViewController.m
//  Monkey-Defense
//
//  Created by Robert Carlson on 9/15/11.
//  Copyright 2011 Carlson Systems. All rights reserved.
//

#import "Monkey_DefenseViewController.h"
#import "GorillaView.h"
#import "ChimpView.h"
#import "TamarinView.h"
#import "OakTreeView.h"
#import "MonkeyTemplateView.h"

@implementation Monkey_DefenseViewController

@synthesize monkeyToBuild;
@synthesize originalTouch;
@synthesize attackField;
@synthesize spawnField;

//Game Events
-(void)beginGame{
  [NSTimer scheduledTimerWithTimeInterval:2.0
                                   target:self
                                 selector:@selector(spawnEnemyMonkey)
                                 userInfo:nil
                                  repeats:YES];
}
-(void)drawMap{
  UIImageView *basicMap = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"map_basic.png"]];
  [basicMap setFrame:CGRectMake(0, 0, 1024, 768)];
  [self.view addSubview:basicMap];
  [basicMap release];
  
  UIImageView *enemySpawn = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"enemy_spawn.png"]];
  [enemySpawn setFrame:CGRectMake(924, 0, 100, 500)];
  [self.view addSubview:enemySpawn];
  [enemySpawn release];
  
  self.attackField = CGRectMake(0, 0, 900, 500);
  self.spawnField = CGRectMake(924, 0, 100, 500);
}

//Template Code
-(void)drawTemplates{
  MonkeyTemplateView *gorillaViewTemplate = [[MonkeyTemplateView alloc] init:[UIImage imageNamed:@"gorilla_icon.png"] frame:CGRectMake(0, 650, 100, 100)];
  gorillaViewTemplate.monkeyType = Gorilla;
  [self setupMonkeyTemplateEvents:gorillaViewTemplate];
  [self.view addSubview:gorillaViewTemplate];
  [gorillaViewTemplate release];
  
  MonkeyTemplateView *chimpViewTemplate = [[MonkeyTemplateView alloc] init:[UIImage imageNamed:@"chimp_icon.png"] frame:CGRectMake(100, 650, 100, 100)];
  chimpViewTemplate.monkeyType = Chimp;
  [self setupMonkeyTemplateEvents:chimpViewTemplate];
  [self.view addSubview:chimpViewTemplate];
  
  MonkeyTemplateView *tamarinViewTemplate = [[MonkeyTemplateView alloc] init:[UIImage imageNamed:@"tamarin_icon.png"] frame:CGRectMake(200, 650, 100, 100)];
  tamarinViewTemplate.monkeyType = Tamarin;
  [self setupMonkeyTemplateEvents:tamarinViewTemplate];
  [self.view addSubview:tamarinViewTemplate];
}
-(void)setupMonkeyTemplateEvents:monkeyTemplateView{
  [monkeyTemplateView addTarget:self
                         action:@selector(clickMonkeyTemplate:event:) 
               forControlEvents:UIControlEventTouchDown];
  [monkeyTemplateView addTarget:self
                         action:@selector(createMonkeyFromTemplate:event:) 
               forControlEvents:UIControlEventTouchDragOutside];
  [monkeyTemplateView addTarget:self
                         action:@selector(placeMonkeyFromTemplate:event:) 
               forControlEvents:UIControlEventTouchUpOutside];
  [monkeyTemplateView addTarget:self
                         action:@selector(undoMonkeyFromTemplate:event:) 
               forControlEvents:UIControlEventTouchUpInside];
}
-(void)clickMonkeyTemplate:(MonkeyTemplateView*)sender event:(UIEvent*)event{
  UITouch *t = [[[event allTouches] allObjects] objectAtIndex:[[event allTouches] count] - 1];
  self.originalTouch = [t locationInView:sender];
}
-(void)createMonkeyFromTemplate:(MonkeyTemplateView*)sender event:(UIEvent*)event{
  UITouch *t = [[[event allTouches] allObjects] objectAtIndex:[[event allTouches] count] - 1];
  CGPoint pt = [t locationInView:[self view]];
  int x = pt.x - self.originalTouch.x;
  int y = pt.y - self.originalTouch.y;
  
  if(!self.monkeyToBuild){
    switch (sender.monkeyType) {
      case Gorilla:
        self.monkeyToBuild = [[GorillaView alloc] initWithLocation:x y:y];
        break;
      case Chimp:
        self.monkeyToBuild = [[ChimpView alloc] initWithLocation:x y:y];
        break;
      case Tamarin:
        self.monkeyToBuild = [[TamarinView alloc] initWithLocation:x y:y];
        break;
      default:
        break;
    }
    [self.view addSubview:self.monkeyToBuild];
  }else{
    [self.monkeyToBuild setFrame:CGRectMake(x, y, self.monkeyToBuild.frame.size.width, self.monkeyToBuild.frame.size.height)];
  }
}
-(void)placeMonkeyFromTemplate:(MonkeyTemplateView *)sender event:(UIEvent*)event{
  CGRect oldFrame = self.monkeyToBuild.frame;
  CGRect fixedFrame = CGRectMake(round(oldFrame.origin.x / 100) * 100, round(oldFrame.origin.y / 100) * 100, oldFrame.size.width, oldFrame.size.height);
  CGRect overFrame;
  //is it withing the playable zone?
  if(!CGRectIntersectsRect(fixedFrame, self.attackField)){
    [self undoMonkeyFromTemplate:sender event:event];
    return;
  }
  //is it overlapping an existing blocker?
  for(UIView *view in self.view.subviews){
    overFrame = view.frame;
    if(CGRectContainsRect(fixedFrame, view.frame)){
      if([view isKindOfClass:[MonkeyView class]]){
        [self undoMonkeyFromTemplate:sender event:event];
        return;
      }
    }
  }
  
  [self.monkeyToBuild setFrame:fixedFrame];
  [self.monkeyToBuild release];
  self.monkeyToBuild = nil;
}
-(void)undoMonkeyFromTemplate:(MonkeyTemplateView *)sender event:(UIEvent*)event{
  [self.monkeyToBuild removeFromSuperview];
  [self.monkeyToBuild release];
  self.monkeyToBuild = nil;
}

//Enemy Code
-(void)spawnEnemyMonkey{
  int x = self.spawnField.origin.x;
  int y = (arc4random() % (int)floor(self.spawnField.size.height / 100) * 100) + self.spawnField.origin.y;
  
  OakTreeView *oakTreeView = [[OakTreeView alloc] initWithLocation:x y:y];
  oakTreeView.Unit = [[Tree alloc] init];
  [self.view addSubview:oakTreeView];
  [self pursue:oakTreeView];
  
  [oakTreeView release];
}
-(void)pursue:(UnitView*)unitView{
  /* 
  int newDistance;
  int distance;
  int x = monkeyView.frame.origin.x;
  int y = monkeyView.frame.origin.y;
 
  //Get New Target (Closest)
  if(monkeyView.Target == nil){
    for(UIView* view in self.view.subviews){
      if([view isKindOfClass:MonkeyView.class] && view != monkeyToBuild){
        if(((MonkeyView*)view).Monkey.Team != monkeyView.Monkey.Team){
          if(monkeyView.Monkey.Team == Computer && ){
          newDistance = abs(view.frame.origin.x - monkeyView.frame.origin.x);
          if(newDistance < distance || distance == 0){
            monkeyView.Target = (MonkeyView*)view;
            distance = newDistance;
          }
          }
        }
      }
    }
  }
  
  if(monkeyView.Target != nil){
    //Chase Target
    [MonkeyView animateWithDuration:3
                              delay:0 
                            options:0 
                         animations:^{
                           monkeyView
                         }
                         completion:^(BOOL completed){
                         }];
  }
   */
}

//System Events
-(void)viewDidLoad{
  [super viewDidLoad];
  [self drawMap];
  [self drawTemplates];
  [self beginGame];
}
-(void)viewDidUnload{
  [super viewDidUnload];
}
-(void)dealloc{
  [super dealloc];
}
-(void)didReceiveMemoryWarning{
  [super didReceiveMemoryWarning];
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
  return YES;
}

@end